package com.jjb.www.ui.activity;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import com.blankj.utilcode.util.GsonUtils;
import com.hjq.bar.TitleBar;
import com.hjq.base.BaseAdapter;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.shape.view.ShapeButton;
import com.hjq.shape.view.ShapeEditText;
import com.hjq.shape.view.ShapeTextView;
import com.hjq.widget.layout.WrapRecyclerView;
import com.jjb.www.R;
import com.jjb.www.app.AppActivity;
import com.jjb.www.http.api.AddReplyApi;
import com.jjb.www.http.api.CurriculumSortApi;
import com.jjb.www.http.api.ReplyApi;
import com.jjb.www.http.api.UpdateImageApi;
import com.jjb.www.http.model.HttpData;
import com.jjb.www.http.model.HttpList;
import com.jjb.www.other.AppConfig;
import com.jjb.www.ui.adapter.AddPhotoAdapter;
import com.jjb.www.ui.fragment.CourseListFragment;
import com.jjb.www.utils.CompressionUtil;
import com.jjb.www.utils.StringBufferUtils;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * author : Android CRG
 * github : https://github.com/getActivity/AndroidProject
 * time   : 2019/03/01
 * desc   : 回复填写
 */
public class ReplyActivity extends AppActivity implements BaseAdapter.OnItemClickListener {
    private TitleBar mTitleBar;
    private ShapeEditText mEtRemark;
    private WrapRecyclerView mRvPhotoList;
    private ShapeButton mBtnSubmit;
    private ShapeTextView mTvProblem;
    private AddPhotoAdapter adapter;
    private View mFooterView;
    //从什么地方跳转进来 details 反馈详情  add问题反馈
    private String framType = "";
    /**
     * 选择图片的张数
     */
    private final int mCount = 6;
    /**
     * 记录选择的数据
     */
    private List<String> mData;

    private List<String> listImg ;


    private String id;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_reply;
    }

    @Override
    protected void initView() {
        mTitleBar = findViewById(R.id.titleBar);
        mEtRemark = findViewById(R.id.et_remark);
        mRvPhotoList = findViewById(R.id.rv_photo_list);
        mBtnSubmit = findViewById(R.id.btn_submit);
        mTvProblem = findViewById(R.id.tv_problem);

        mData = new ArrayList<>();
        adapter = new AddPhotoAdapter(this);
        adapter.setOnItemClickListener(this);

        mRvPhotoList.setLayoutManager(new GridLayoutManager(this, 3));
        mRvPhotoList.setAdapter(adapter);
        mFooterView = LayoutInflater.from(getContext()).inflate(R.layout.item_no_photo, mRvPhotoList, false);
        mRvPhotoList.addFooterView(mFooterView);
        setOnClickListener(mTvProblem, mFooterView,mBtnSubmit);
    }

    @Override
    protected void initData() {
        framType = getString("framType");
        id = getString("id");
        if ("add".equals(framType)){
            mTitleBar.setTitle("新增反馈");
        }
    }

    @Override
    public void onClick(View view) {
        if (view == mTvProblem) {
            startActivity(ProblemActivity.class);
        } else if (view == mFooterView) {
            ImageSelectActivity.start(ReplyActivity.this, mCount - adapter.getCount(), new ImageSelectActivity.OnPhotoSelectListener() {
                @Override
                public void onSelected(List<String> data) {
                    mData.addAll(data);
                    if (data.size() == mCount || mData.size() == mCount) {
                        mRvPhotoList.removeFooterView(mFooterView);
                    }
                    adapter.setData(mData);
                }
            });
        }else if (view==mBtnSubmit){
            String remark = "";
            listImg = new ArrayList<>();
            if ("".equals(mEtRemark.getText().toString().trim())){
                toast("请输入需要反馈给我们的问题或者意见");
                return;
            }
            remark = mEtRemark.getText().toString().trim();

            if ("details".equals(framType)){
                if (!mData.isEmpty()) {
                    List<File> list = new ArrayList<>();
                    for (int i = 0; i < mData.size(); i++) {
                        list.add(new File(mData.get(i)));
                    }
                    compression(remark,list);
                }else {
                    putData(remark,null);
                }
            }else {
                if (!mData.isEmpty()) {
                    List<File> list = new ArrayList<>();
                    for (int i = 0; i < mData.size(); i++) {
                        list.add(new File(mData.get(i)));
                    }
                    compression(remark,list);
                }else {
                    putAddData(remark,null);
                }
            }


        }
    }

    private void compression(String remark, List<File> list) {
        Luban.with(this)
                .load(list)
                .ignoreBy(100)
                .setTargetDir(CompressionUtil.getPath(this))
                .filter(new CompressionPredicate() {
                    @Override
                    public boolean apply(String path) {
                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                    }
                })
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(File file) {
                        List<File> list = new ArrayList<>();
                        list.add(file);
                        updateImage(remark,list);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                }).launch();
    }
    private void updateImage(String remark,List<File> list) {
        for (File file:list) {
            EasyHttp.post(this)
                    .api(new UpdateImageApi()
                            .setFile(file)
                    ).request(new HttpCallback<HttpData<UpdateImageApi.Bean>>(this) {

                @Override
                public void onSucceed(HttpData<UpdateImageApi.Bean> data) {
                    listImg.add(data.getData().getAttach_id());
                    if (listImg.size()==mData.size()){
                        String img = StringBufferUtils.arrToStr(listImg,",");
                        if ("details".equals(framType)){
                            putData(remark,img);
                        }else {
                            putAddData(remark,img);
                        }

                    }
                }
            });
        }
    }
    private void putData(String content,String imgList) {
        EasyHttp.post(this)
                .api(new ReplyApi()
                .setId(id)
                        .setImg(imgList)
                .setContent(content))
                .request(new HttpCallback<Void>(this) {

                    @Override
                    public void onSucceed(Void data) {
                        toast("回复成功");
                        finish();
                    }

                });
    }

    private void putAddData(String content,String imgList) {
        Map map = new LinkedHashMap();
        map.put("Product", android.os.Build.PRODUCT);
        map.put("CPU_ABI", android.os.Build.CPU_ABI);
        map.put("TAGS", android.os.Build.TAGS);
        map.put("BASE", android.os.Build.VERSION_CODES.BASE);
        map.put("MODEL", android.os.Build.MODEL);
        map.put("SDK", android.os.Build.VERSION.SDK);
        map.put("RELEASE", android.os.Build.VERSION.RELEASE);
        map.put("DEVICE", android.os.Build.DEVICE);
        map.put("DISPLAY", android.os.Build.DISPLAY);
        map.put("BRAND", android.os.Build.BRAND);
        map.put("BOARD", android.os.Build.BOARD);
        map.put("FINGERPRINT", android.os.Build.FINGERPRINT);
        map.put("ID", android.os.Build.ID);
        map.put("MANUFACTURER", android.os.Build.MANUFACTURER);
        map.put("USER", android.os.Build.USER);
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(GsonUtils.toJson(map));
        } catch (Exception e) {
            e.printStackTrace();
        }
        EasyHttp.post(this)
                .api(new AddReplyApi()
                        .setImg(imgList)
                        .setContent(content)
                .setPhone_type("android")
                .setVersion(AppConfig.getVersionName())
                .setSystemInfo(jsonObject.toString()))
                .request(new HttpCallback<Void>(this) {

                    @Override
                    public void onSucceed(Void data) {
                        toast("反馈成功");
                        finish();
                    }

                });
    }

    @Override
    public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
        adapter.removeItem(position);
        if (adapter.getData() != null && adapter.getData().size() < mCount && mRvPhotoList.getFooterViews().isEmpty()) {
            mRvPhotoList.addFooterView(mFooterView);
        }
    }
}